package com.ming.demo.service.impl;

import com.alibaba.fastjson.JSON;
import com.ming.demo.bean.Audience;
import com.ming.demo.bean.WeChat;
import com.ming.demo.mapper.WeChatMapper;
import com.ming.demo.service.LoginService;
import com.ming.demo.utils.HttpClient4;
import com.ming.demo.utils.JwtTokenUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class LoginServiceImpl implements LoginService {
    @Autowired
    private WeChatMapper weChatMapper;

    @Autowired
    private Audience audience;

    @Override
    public String getToken(String code) {
        // 获取code
        System.out.println(code);
        // 发送get请求，获取
        // 拼接URL
        String url = "https://api.weixin.qq.com/sns/jscode2session?appid=wx89f8d8055ab82293&secret=95a402883443e81e1689aa0ae2b18f35&js_code=" + code + "&grant_type=authorization_code";

        String res = HttpClient4.doGet(url);
        // 发送get请求，获取
        WeChat weiChat = JSON.parseObject(res, WeChat.class);
        System.out.println(weiChat);
        // 写入数据库中
        int res1 = weChatMapper.insertWeChat(weiChat);
        if(res1 == 1){
            // 生成jwt
            String openId = weiChat.getOpenid();
            String session_key = weiChat.getSession_key();
            String token = JwtTokenUtil.createJWT(openId, session_key, "admin", audience);
            return token;
        }
        return null;
    }


    @Override
    public void testToken(String token) {
        try {
            System.out.println(JwtTokenUtil.getUserId(token, audience.getBase64Secret()));
            System.out.println(JwtTokenUtil.getUsername(token,audience.getBase64Secret()));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
